<template>
  <div class="cesium-map">
    <div id="cesiumContainerSplit"></div>

    <div class="control-box">
      <div class="box-title">
        <span>右屏模型信息</span>
      </div>

      <div class="box-body">
        <div class="linkage-switch">
          <span>模型联动</span>
          <el-switch v-model="linkage" active-color="#13ce66" inactive-color="#ff4949" @change="linkageMap">
          </el-switch>
        </div>

        <div class="model-box">
          <div v-for="(item, index) in modelList" :key="index" class="model-item">
            <div class="item-left">
              <span class="beyond-txt">{{ item.serverName }}</span>
            </div>

            <div class="item-right">
              <img v-for="(option, key) in item.control" :key="key"
                   :src="require(`@/assets/image/leftSub/${option.icon}`)"
                   alt="" @click.stop="operateModel(item, option)">
            </div>
          </div>
        </div>

        <div class="add-box">
          <i class="el-icon-plus" @click="openModelPopover"></i>
          <span @click="openModelPopover">添加</span>

          <div v-if="showAdd" class="popover-box">
            <div v-for="(item, index) in modelPopover" :key="index" class="item" @click="openModelDialog(item)">
              <span>{{ item }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div v-if="viewer">
      <load-model-dialog v-show="isShowLoadModel" ref="modelDialogEle" :globalViewer="viewer" :popupItemType="modelType"
                         @appendModelNode="appendModelNode" @close="closeModelDialog"></load-model-dialog>
      <load-layer-dialog v-show="isShowLoadLayer" ref="layerDialogEle" :globalViewer="viewer"
                         :selectNode="selectNode"
                         @close="isShowLoadLayer = false"></load-layer-dialog>
    </div>
  </div>
</template>

<script>
import loadModelDialog from '@/components/3DModel/loadModelDialog.vue';
import loadLayerDialog from "@/components/vectorLayer/loadLayerDialog.vue";
import {addskyLayer} from '@/utils/map.js';

export default {
  components: {loadModelDialog, loadLayerDialog},

  data() {
    return {
      isShowLoadLayer: false,
      linkage: true,
      modelList: [],
      showAdd: false,
      // modelPopover: ['三维模型文件', '三维场景服务', '三维服务'],
      modelPopover: ['三维模型文件', '三维服务', '影像数据'],
      modelNodeIndex: 1,
      modelDefaultIndex: 1,
      modelType: '',
      isShowLoadModel: false,
      componentId: '',
      tdtToken: "1fd463af45319bc45b394dac4a87006b",
      terrainShow: false,
      selectNode: {
        label: '影像数据'
      },
    };
  },

  created() {
    if (window.appSettings) {
      const {token} = window.appSettings.engineering.baseMap.tianditu
      if (token) {
        this.tdtToken = token;
      }
      this.terrainShow =
          window.appSettings.engineering.baseMap.other.terrainShow;
    }
    this.viewer = null;
    this.handler = null;
    this.cameraChange = null;
  },

  async mounted() {
    this.createdMap();
    let imageUrl = window.serviceUrl.skyImageUrl + `&tk=${this.tdtToken}`;
    if (process.env.NODE_ENV === 'development') {
      try {
        const data = await this.$get('local/local.json')
        imageUrl = data.imageUrl
      } catch (error) {
        imageUrl = window.serviceUrl.skyImageUrl
      }
    }
    addskyLayer(this.viewer, imageUrl);
    this.$emit('linkageMap', true);
  },

  beforeDestroy() {
    this.$emit('linkageMap', false);
  },

  methods: {

    appendModelNode(option) {
      option.control = [
        {
          icon: '当前定位.png',
          name: '定位',
          isCheck: false
        },
        {
          icon: '删除.png',
          name: '删除',
          isCheck: false
        },
        {
          icon: '显示.png',
          name: '显示',
          isCheck: false
        }
      ];
      this.modelList.push(option);
    },

    // 关闭弹窗
    closeModelDialog() {
      this.isShowLoadModel = false;
    },
    // 初始化地图
    createdMap() {
      var cesiumTerrainProvider = new Cesium.CesiumTerrainProvider({
        url: window.serviceUrl.terrainUrl
      });
      this.viewer = new Cesium.Viewer('cesiumContainerSplit', {
        terrainProvider: cesiumTerrainProvider,
        useBrowserRecommendedResolution: true,
        selectionIndicator: false,
        homeButton: false,
        animation: false,  //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false,  //是否显示点击要素之后显示的信息
        imageryProvider: false,
        fullscreenButton: false,
        shouldAnimate: true,
        requestRenderMode: true,
      });
      this.viewer.scene.globe.depthTestAgainstTerrain = false;
      this.viewer.scene.primitives.destroyPrimitives = false;
      this.viewer.scene.postProcessStages._fxaa.enabled = true;
      this.viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
      this.viewer._cesiumWidget._creditContainer.style.display = "none";
      this.viewer.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

      //指北针
      let options = {};
      // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
      options.defaultResetView = Cesium.Rectangle.fromDegrees(80, 22, 130, 50);
      // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
      options.enableCompass = true;
      // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
      options.enableZoomControls = false;
      // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
      options.enableDistanceLegend = false;
      // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
      options.enableCompassOuterRing = true;
      CesiumNavigation.umd(this.viewer, options);
    },

    // 判断资源是否存在
    async fileExist(url) {
      let isExist = null;
      try {
        let res = await this.$get(url);
        isExist = true;
      } catch (error) {
        isExist = false;
      }
      return isExist;
    },

    // 获取当前节点数据
    getCurNodeData() {
      const simulationOption = {
        "id": "1-1",
        "level": 2,
        "label": "三维模型",
        "children": this.modelList,
        "icon": "三维模型_s.png",
        "isCheck": true,
        "control": [
          {
            "name": "添加",
            "isCheck": false,
            "icon": "添加.png"
          },
          {
            "name": "删除",
            "isCheck": false,
            "icon": "删除.png"
          },
          {
            "name": "显示",
            "isCheck": false,
            "icon": "显示.png"
          }
        ]
      };
      return simulationOption;
    },

    // 判断树节点是否为空
    isFirstUpdataNode() {
      return this.modelList.length <= 1 ? true : false;
    },

    linkageMap() {
      this.$emit('linkageMap', this.linkage);
    },

    // 提示
    message(message = '警告', type = 'warning') {
      this.$message({
        message: message,
        type: type
      });
    },

    // 打开加载模型弹窗
    openModelDialog(option) {
      this.modelType = option;
      switch (option) {
        case '三维模型文件':
          this.modelPlaceholder = 'glb/gltf';
          this.isShowLoadModel = true;
          break;

        case '三维场景服务':
          this.modelPlaceholder = '三维文件';
          this.isShowLoadModel = true;
          break;

        case '三维服务':
          this.modelPlaceholder = 'merge_tile.json/tileset.json';
          this.isShowLoadModel = true;
          break;
        case '影像数据':
          this.isShowLoadLayer = true;
          break

        default:
          break;
      }

      this.showAdd = false;
    },

    openModelPopover() {
      this.showAdd = !this.showAdd;
    },

    // 模型列表操作
    operateModel(listItem, option) {
      let modelList = this.modelList;
      if (option.name == '显示') {
        modelList.forEach(item => {
          if (item.resourceId == listItem.resourceId) {
            item.control.forEach(e => {
              if (e.name == '显示') {
                e.isCheck = !e.isCheck;
                e.icon = e.isCheck ? '隐藏.png' : '显示.png';
              }
            });
          }
        });
        this.modelList = modelList;
      }

      const {resourceId} = listItem;
      switch (option.name) {
        case '定位':
          this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.locateModel(resourceId);
          break;

        case '删除':
          this.$confirm('此操作将删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            for (let i = 0; i < modelList.length; i++) {
              const item = modelList[i];
              if (item.resourceId == listItem.resourceId) {
                modelList.splice(i, 1);
                i++;
              }
            }
            this.modelList = modelList;
            this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.removeModel(resourceId);
            this.message('删除成功!', 'success');
          }).catch(() => {
            this.message('已取消删除', 'info');
          });
          break;

        case '显示':
          this.$refs.modelDialogEle && this.$refs.modelDialogEle._Model.hideModel(resourceId, !option.isCheck);
          break;

        default:
          break;
      }
    },

    // 检查是否有重名
    unitListName(list, n) {
      function check(name) {
        let n = name.match(/[^\.]*/)[0];
        return function (a) {
          return a.indexOf(n) == 0;
        };
      }

      list = list.filter(check(n));
      let on = n.match(/([^\.]*)(.*)/);

      // 重名文件最多10000个
      for (let i = 1; i < 10000; i++) {
        let nn = on[1] + '_' + String(i);
        if (!list.find((element) => (element == nn + on[2])))
          return nn + on[2];
      }
    },
  }
}
</script>

<style lang="less" scoped>
.cesium-map,
#cesiumContainerSplit {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 1;
}

.cesium-map {
  position: relative;

  .control-box {
    position: absolute;
    left: 20px;
    top: 20px;
    width: 235px;
    height: 170px;
    padding: 10px 15px;
    box-sizing: border-box;
    border: 2px solid #ffffff;
    background-color: #313131;
    z-index: 11;
    font-size: 12px;
    color: #acacac;

    .box-title {
      display: flex;
      align-items: center;
      margin-bottom: 10px;
    }

    .box-body {
      .linkage-switch {
        display: flex;
        align-items: center;
        margin-bottom: 10px;

        /deep/ .el-switch {
          width: 25px;
          height: 15px;
          margin-left: 8px;

          .el-switch__core {
            width: 100%;
            height: 100%;

            &::after {
              width: 10px;
              height: 10px;
            }
          }
        }

        /deep/ .el-switch.is-checked .el-switch__core::after {
          left: 100%;
          margin-left: -12px;
        }
      }

      .model-box {
        height: 80px;
        margin-bottom: 3px;
        overflow-y: auto;

        .model-item {
          position: relative;
          display: flex;
          align-items: center;
          width: 100%;
          padding: 2px 10px;
          box-sizing: border-box;
          border-bottom: 1px solid #454545;

          .item-left {
            width: 50%;

            span {
              display: inline-block;
              width: 99%;
              font-size: 14px;
            }
          }

          .item-right {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            width: 50%;
            column-gap: 10px;

            img {
              width: 12px;
              height: 12px;
              cursor: pointer;
            }
          }
        }
      }

      .add-box {
        position: relative;
        display: flex;
        justify-content: center;
        align-items: center;
        color: #78a9ff;
        cursor: pointer;

        span {
          margin-left: 8px;
        }

        .popover-box {
          position: absolute;
          top: 30px;
          left: 50%;
          transform: translateX(-45%);
          width: 112px;
          background: rgba(0, 0, 0, 0.8);
          box-shadow: 0px 2px 4px 0px rgba(0, 0, 0, 0.2);
          border-radius: 8px;
          border: 1px solid #444444;
          backdrop-filter: blur(2px);
          padding: 6px 4px;
          box-sizing: border-box;
          pointer-events: all;
          z-index: 11;

          .item {
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: 32px;
            border-radius: 4px;
            font-size: 14px;
            font-family: AlibabaPuHuiTiR;
            color: #ffffff;

            &:hover {
              background-color: rgba(74, 88, 120, 0.4);
            }
          }
        }
      }
    }
  }

  .dialog-box {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.8);
    z-index: 999;

    .box-content {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      padding: 15px;
      box-sizing: border-box;
      border: 1px solid #008aff70;
      border-radius: 5px;
      box-shadow: 0 4px 15px 1px #02213bb3;
      background-color: #173147cc;

      .content-header {
        display: flex;
        align-items: center;
        width: 400px;
        padding: 0 0 15px 0;
        box-sizing: border-box;
        font-size: 18px;
        font-weight: 400;
        color: #a4e6ff;
      }

      .content-body {
        /deep/ .el-form {
          .el-form-item {
            &:last-child {
              display: flex;
              justify-content: flex-end;
              margin-bottom: 0;
            }

            .el-form-item__label {
              color: #ffffff;
            }

            .el-input__inner {
              background-color: rgba(3, 78, 114, 0.52);
              border-radius: 5px;
              border: 1px solid #459bec;
              box-sizing: border-box;
              font-size: 13px;
              color: #ffffff;
            }

            .el-button {
              padding: 6px 12px;
            }
          }

          .position-box {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .el-form-item {
              display: flex;
              align-items: center;
              width: 320px;
              margin-bottom: 18px;

              .el-form-item__content {
                margin-left: 0px !important;
              }
            }
          }
        }
      }
    }
  }
}

.beyond-txt {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  -o-text-overflow: ellipsis;
  word-break: break-all;
}
</style>

<style lang="less">
.compass {
  top: 30px;
  right: 20px;

  .compass-rotation-marker,
  .compass-outer-ring {
    width: 90%;
    height: 90%;
  }

  .compass-outer-ring {
    background: url(~@/assets/image/toolBar/zhibeizhen.png) no-repeat;
    background-size: 100% 100%;
    background-size: 100%;
  }

  .compass-outer-ring-background,
  .compass-gyro-background,
  .compass-gyro {
    display: none;
  }
}

.cesium-performanceDisplay-defaultContainer {
  display: none !important;
}
</style>